package com.example.config;


import com.example.entity.vo.SysUserVo;
import com.example.service.ISysRoleRightService;
import com.example.service.SysUsrService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class CutomerRealm extends AuthorizingRealm {
    @Autowired
    SysUsrService sysUsrService;
    @Autowired
    ISysRoleRightService iSysRoleRightService;

    //鉴权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取已认证的当前对象
        SysUserVo userVo = (SysUserVo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();


        //将当前用户可访问的权限资源添加到鉴权类中
        info.addRole(userVo.getRole().getRoleName());
//
//        List<SysRight> rightList=userVo.getRole().getRights();
//        for (SysRight temp:rightList) {
//            if(StringUtils.isNotEmpty(temp.getRightUrl().trim())){
//                info.addStringPermission(temp.getRightCode());
//            }
//        }

        info.addStringPermissions(iSysRoleRightService.getRightByRoleId(userVo.getRole().getRoleId()));



        return info;
    }

    //身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
        String password=new String(token.getPassword());

        SysUserVo sysUser= sysUsrService.getUserByUsrName(userName);
        //账号或密码错误！
        if(sysUser==null){
            throw  new UnknownAccountException();
        }
        //账号不可用
        if(sysUser.getUsrFlag()!=1){
            throw new LockedAccountException();
        }


        SimpleAuthenticationInfo info =new SimpleAuthenticationInfo(sysUser,sysUser.getUsrPassword(),String.valueOf(userName));
        return info;
    }
}
